<?php

namespace app\controller\api;

use app\util\ReturnCode;
use app\model\CheckItem as CheckItemModel;
use app\model\RailwayStation as RailwayStationModel;
use app\model\Railway as RailwayModel;
use app\model\CheckRecord as CheckRecordModel;
use think\exception\ValidateException;
class CheckItem extends Base
{
    public function lists()
    {

        $rid = $this->request->get('rid', 0);
        // $sid = $this->request->get('sid', 0);
        $crid = $this->request->get('crid', 0);

        // 先查询站点状态
        // $station = RailwayStationModel::where(['id' => $sid])->find();

        // 如果站点状态不是封锁状态(status>1),则返回空数组
        // if (!$station || $station['status'] <= 1) {
        //     return $this->buildSuccess([]);
        // }

        // 查询检查项目列表
        $lists = CheckItemModel::where([
            ['railway_id', '=', $rid],
            // ['start_id', '=', $sid],
            ['check_record_id', '=', $crid],
        ])
            ->field('id, check_record_id, railway_id,arrival_id, start_id, end_id, user_id, user_name, type_id, type, type_name, content, train_no, station_time, boarding_time, departure_time, arrival_time, complete_time, images_url, status, create_time, update_time')
            ->select()
            ->toArray();

        return $this->buildSuccess($lists);
    }

    /**
     * 获取检查记录列表
     */
    public function record()
    {
        $rid = $this->request->get('rid', 0);
        $status = $this->request->get('status', '');
        $user_id = $this->request->get('user_id', 0);
        $keywords = $this->request->get('keywords', '');
        $userInfo = $this->getUserInfo();

        $railway = RailwayModel::where(['id' => $rid])->find();
        $railway_name = $railway ? $railway['name'] : '';

        $railway_stations = RailwayStationModel::column('name', 'id');
        // 构建查询条件
        $where = [
            ['delete_time', '=', null]
        ];

        // 如果不是管理员，只查看自己的记录
        if (!$userInfo['sys']) {
            $where[] = ['user_id', '=', $userInfo['id']];
        }

        // 如果指定了铁路ID
        if ($rid) {
            $where[] = ['railway_id', '=', $rid];
        }

        // 如果指定了状态
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }

        // 如果指定了检查人员
        if ($user_id) {
            $where[] = ['user_id', '=', $user_id];
        }

        // 如果有关键词搜索
        if ($keywords) {
            $where[] = ['type_name|content|train_no', 'like', '%'.$keywords.'%'];
        }

        // 查询记录列表
        $lists = CheckItemModel::where($where)
            ->field('id, railway_id, arrival_id, direction, start_id, end_id, user_id, user_name, type_id, type, type_name, content, train_no, station_time, boarding_time, departure_time, arrival_time, complete_time, images_url, status, create_time')
            ->order('create_time', 'desc')
            ->select()
            ->each(function ($item) use ($railway_name, $railway_stations) {
                // 添加铁路名称
                $item['railway_name'] = $railway_name;

                // 格式化时间
                $timeFields = ['create_time', 'station_time', 'boarding_time', 'departure_time', 'arrival_time', 'complete_time'];
                foreach ($timeFields as $field) {
                    if (isset($item[$field])) {
                        $timestamp = intval($item[$field]);
                        if ($timestamp > 0) {
                            $item[$field] = date('Y-m-d H:i:s', $timestamp);
                        } else {
                            $item[$field] = '';
                        }
                    } else {
                        $item[$field] = '';
                    }
                }
                // 添加车站名称
                $item['start_text'] = $railway_stations[$item['start_id']] ?? '';
                $item['end_text'] = $railway_stations[$item['end_id']] ?? '';
                // 添加方向文本
                $item['direction_text'] = $item['direction'] === 1 ? '上行' : '下行';
            })
            ->toArray();

        return $this->buildSuccess($lists);
    }

    /**
     * 获取检查记录详情
     */
    public function record_info()
    {
        $id = $this->request->get('id', 0);
        if (!$id) {
            return $this->buildFailed(ReturnCode::INVALID, '参数错误');
        }

        $detail = CheckItemModel::where([
            ['id', '=', $id],
            ['delete_time', '=', null]
        ])->find()->toArray();

        if (!$detail) {
            return $this->buildFailed(ReturnCode::INVALID, '未找到相关记录');
        }

        // 获取铁路名称
        $railway = RailwayModel::where(['id' => $detail['railway_id']])->find();
        $detail['railway_name'] = $railway ? $railway['name'] : '';

        // 获取车站名称
        $railway_stations = RailwayStationModel::column('name', 'id');
        $detail['start_text'] = $railway_stations[$detail['start_id']] ?? '';
        $detail['end_text'] = $railway_stations[$detail['end_id']] ?? '';
        $detail['station_name'] = $railway_stations[$detail['arrival_id']] ?? '';
        
        // 添加方向文本
        $detail['direction_text'] = $detail['direction'] === 1 ? '上行' : '下行';

        // 格式化时间
        $timeFields = ['create_time', 'station_time', 'boarding_time', 'departure_time', 'arrival_time', 'complete_time'];
        foreach ($timeFields as $field) {
            if (isset($detail[$field]) && $detail[$field] > 0) {
                $detail[$field] = date('Y-m-d H:i:s', intval($detail[$field]));
            } else {
                $detail[$field] = '';
            }
        }

        // 处理图片URL
        if (isset($detail['images_url']) && $detail['images_url']) {
            $detail['images_url'] = $detail['images_url'];
        } else {
            $detail['images_url'] = '';
        }

        // 处理备注内容
        if (isset($detail['content']) && $detail['content']) {
            $detail['content'] = $detail['content'];
        } else {
            $detail['content'] = '';
        }

        // 处理车次信息
        if (isset($detail['train_no']) && $detail['train_no']) {
            $detail['train_no'] = $detail['train_no'];
        } else {
            $detail['train_no'] = '';
        }

        return $this->buildSuccess($detail);
    }

    //检查
    public function check()
    {
        $userInfo = $this->getUserInfo();
        $user_id = $userInfo['id'];
        $input = $this->request->post();
        try {
            validate(\app\validate\Check::class)->check($input);
        } catch (ValidateException $e) {
            return $this->buildFailed(ReturnCode::INVALID, $e->getError());
        }

        $item = CheckItemModel::where(['id' => $input['item_id']])->find();
        if (!$item) {
            return $this->buildFailed(ReturnCode::INVALID, '未找到检查项目');
        }
        if ($item['check_record_id'] != $input['crid']) {
            return $this->buildFailed(ReturnCode::INVALID, '检查项目异常');
        }

        // 验证user_id,如果项目已经有user_id且不是当前用户,则不允许操作
        if ($item['user_id'] && $item['user_id'] != $user_id) {
            return $this->buildFailed(ReturnCode::INVALID, '该项目已被其他用户操作,您无权继续操作');
        }

        $check_record = CheckRecordModel::where(['id' => $input['crid']])->find();

        $data = [];
        $updateData = [];

        // 先判断是什么类型，type 1 上下行检查，2 普通检查
        if ($item['type'] == 1) {
            // 上下行检查 流程 到站 检查 开车 到达 检查完成时间
            switch ($input['progress']) {
                case 0: // 到站时间
                    $updateData = [
                        'station_time' => substr($input['station_time'], 0, 10),
                        'status' => 1,
                        'user_id' => $user_id,
                        'user_name' => $userInfo['name'],
                    ];
                    // 更新check_record状态为进行中
                    CheckRecordModel::where(['id' => $input['crid']])->update([
                        'status' => 1,
                        'update_time' => time()
                    ]);
                    // 更新railway_station状态
                    RailwayStationModel::where([
                        ['id', 'in', $check_record['range_ids']]
                    ])->update([
                        'status' => 3,
                    ]);
                    break;
                case 1: // 检查信息
                    $updateData = [
                        'train_no' => $input['train_no'],
                        'arrival_id' => $input['arrival_id'],
                        'images_url' => $input['images_url'],
                        'boarding_time' => substr($input['boarding_time'], 0, 10),
                        'content' => $input['content'],
                        'status' => 1
                    ];
                    break;
                case 2: // 开车时间
                    $updateData = [
                        'departure_time' => substr($input['departure_time'], 0, 10),
                        'status' => 1
                    ];
                    break;
                case 3: // 到达时间
                    $updateData = [
                        'arrival_time' => substr($input['arrival_time'], 0, 10),
                        'status' => 1
                    ];
                    break;
                case 4: // 完成
                    $updateData = [
                        'complete_time' => time(),
                        'status' => 2
                    ];
                    break;
            }
        } else {
            // 普通检查 流程 到站 检查 完成
            switch ($input['progress']) {
                case 0: // 到站时间
                    $updateData = [
                        'station_time' => substr($input['station_time'], 0, 10),
                        'status' => 1,
                        'user_id' => $user_id,
                        'user_name' => $userInfo['name'],
                    ];
                    // 更新check_record状态为进行中
                    CheckRecordModel::where(['id' => $input['crid']])->update([
                        'status' => 1,
                    ]);
                    // 更新railway_station状态
                    RailwayStationModel::where([
                        ['id', 'in', $check_record['range_ids']]
                    ])->update([
                        'status' => 3,
                    ]);
                    break;
                case 1: // 检查信息
                    $updateData = [
                        'images_url' => $input['images_url'],
                        'content' => $input['content'],
                        'complete_time' => time(),
                        'status' => 2
                    ];
                    break;
            }
        }

        // 更新检查项目
        if (!empty($updateData)) {
            CheckItemModel::where(['id' => $input['item_id']])->update($updateData);

            // 更新主记录状态
            if (isset($updateData['status']) && $updateData['status'] == 2) {
                // 检查是否所有项目都已完成
                $allItems = CheckItemModel::where(['check_record_id' => $input['crid']])->select();
                $allCompleted = true;
                foreach ($allItems as $checkItem) {
                    if ($checkItem['status'] != 2) {
                        $allCompleted = false;
                        break;
                    }
                }

                // 如果所有项目都完成，更新主记录状态为完成
                if ($allCompleted) {
                    // 更新check_record状态
                    CheckRecordModel::where(['id' => $input['crid']])->update([
                        'status' => 2,
                        'update_time' => time()
                    ]);

                    // 更新区间内所有railway_station状态
                    RailwayStationModel::where([
                        ['id', 'in', $check_record['range_ids']]
                    ])->update([
                        'status' => 4,
                        'check_item_ids' => null
                    ]);
                }
            }
        }

        return $this->buildSuccess();
    }
}
